package com.xiaodu.acer.phoneplay.presenter;

import com.xiaodu.acer.phoneplay.bean.LoginBean;
import com.xiaodu.acer.phoneplay.common.Constant;
import com.xiaodu.acer.phoneplay.common.rx.RxBus;
import com.xiaodu.acer.phoneplay.common.rx.RxHttpReponseCompat;
import com.xiaodu.acer.phoneplay.common.rx.subscriber.ProgressSubcriber;
import com.xiaodu.acer.phoneplay.common.util.FormatVerificationUtils;
import com.xiaodu.acer.phoneplay.presenter.contract.LoginContract;
import com.xiaodu.acer.phoneplay.ui.base.BasePresenter;

import javax.inject.Inject;

import library.util.ACache;

/**
 * @author 小杜
 *         邮箱:m15701207383@163.com
 * @version V1.0
 * @Description: ${TODO}(用一句话描述该文件做什么)
 * @date 2018/1/10 13:33
 */

public class LoginPresenter extends BasePresenter<LoginContract.Model, LoginContract.View> {

    @Inject
    public LoginPresenter(LoginContract.Model model, LoginContract.View view) {
        super(model, view);
    }


    public void login(String phone, String pwd) {
        if (FormatVerificationUtils.matcherPhoneNum(phone)) {
            mView.checkPhoneSuccess();
        } else {
            mView.checkPhoneError();
            return;
        }

        mModel.getLogin(phone, pwd)
                .compose( RxHttpReponseCompat.<LoginBean>compatResult())
                .subscribe(new ProgressSubcriber<LoginBean>(mContext, mView) {
                    @Override
                    public void onNext(LoginBean loginBean) {
                        //保存用户信息
                        saveUser(loginBean);
                        //通知View
                        mView.loginSuccess(loginBean);

                        //异步回调给需要用到的地方
                        RxBus.getDefault().post(loginBean.getUser());

                    }


                });
    }

    /**
     * 保存用户信息
     */
    private void saveUser(LoginBean bean) {
        ACache aCache = ACache.get(mContext);
        aCache.put(Constant.TOKEN, bean.getToken());
        aCache.put(Constant.USER, bean.getUser());
    }
}
